package com.edu.neusoft.furniture_sale.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.neusoft.furniture_sale.common.ResponseResult;
import com.edu.neusoft.furniture_sale.common.enums.AppHttpCodeEnum;
import com.edu.neusoft.furniture_sale.dto.UserDto;
import com.edu.neusoft.furniture_sale.entity.User;
import com.edu.neusoft.furniture_sale.mapper.UserMapper;
import com.edu.neusoft.furniture_sale.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * 用户信息(User)表服务实现类
 *
 * @author makejava
 * @since 2024-12-09 23:36:27
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseResult login(UserDto dto, HttpSession session) {
        //1.正常登录：用户名和密码
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //1.1 根据手机号去数据库查询用户信息
            User dbUser = getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, dto.getPhone()));
            //用户不存在，返回错误信息
            if (dbUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");
            }

            //用户存在，校验验证码
            Object codeInSession = session.getAttribute(dto.getPhone());

            if (codeInSession != null && codeInSession.equals(dto.getCode()))  {
                //1.2 校验密码
                String password = dto.getPassword();
                String dbUserPassword = dbUser.getPassword();
                if (password.equals(dbUserPassword)) {
                    session.setAttribute("loginUser", dbUser);
                    log.info("session:----------------" + session.getAttribute("loginUser"));
                    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.ERROR, "验证码错误");
            }
        } else {
            //2.用户名或密码为空，登录失败
            return ResponseResult.errorResult(AppHttpCodeEnum.ERROR_USERNAME_PASSWORD_EMPTY);
        }
    }
}

